package com.zeny.coding.service.impl;


import com.zeny.coding.constants.CourseConstants;
import com.zeny.coding.dto.RoleResourceDto;
import com.zeny.coding.entity.RoleResource;
import com.zeny.coding.entity.RoleResourceExample;
import com.zeny.coding.mapper.RoleResourceMapper;
import com.zeny.coding.service.RoleResourceService;
import com.zeny.coding.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <h2>TODO</h2>
 *
 * @Author Zeny
 */
@Slf4j
@SuppressWarnings("all")
@Service
public class RoleResourceServiceImpl implements RoleResourceService {

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Transactional
    @Override
    public void saveBatch(RoleResourceDto roleResourceDto) {
        //先删除旧的
        String roleId = roleResourceDto.getRoleId();
        RoleResourceExample example = new RoleResourceExample();
        example.createCriteria().andRoleIdEqualTo(roleId);
        this.roleResourceMapper.deleteByExample(example);
        List<String> resourceIds = roleResourceDto.getResourceIds();
        if (CollectionUtils.isEmpty(resourceIds)) {
            log.info("角色-资源分配,资源id为空，删除原来的后直接返回");
            return;
        }
        //新增
        SnowFlake snowFlake = new SnowFlake(CourseConstants.dataCenterId, CourseConstants.machineId);
        for (String resourceId : resourceIds) {
            RoleResource roleResource = new RoleResource();
            roleResource.setId(String.valueOf(snowFlake.nextId()));
            roleResource.setRoleId(roleId);
            roleResource.setResourceId(resourceId);
            this.roleResourceMapper.insertSelective(roleResource);
        }
    }
}
